package com.wjs.examfrog.gateway.filter;

import com.wjs.examfrog.gateway.loadbalance.ConsistencyHash;
import com.wjs.examfrog.gateway.loadbalance.WeightedRoundRobin;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.gateway.config.LoadBalancerProperties;
import org.springframework.cloud.gateway.filter.LoadBalancerClientFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.web.server.ServerWebExchange;

import java.net.URI;

@Slf4j
public class CustomLoadBalancerFilter extends LoadBalancerClientFilter{

    private final DiscoveryClient discoveryClient;

    private final ConsistencyHash consistencyHash;

    private final WeightedRoundRobin weightedRoundRobin;

    public CustomLoadBalancerFilter(LoadBalancerClient loadBalancer,
                                    LoadBalancerProperties properties,
                                    DiscoveryClient discoveryClient) {
        super(loadBalancer, properties);
        this.discoveryClient = discoveryClient;
        consistencyHash = new ConsistencyHash(discoveryClient,5);
        weightedRoundRobin = new WeightedRoundRobin();
    }

    @Override
    protected ServiceInstance choose(ServerWebExchange exchange) {
        String host = ((URI)exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR)).getHost();
        if (StringUtils.equals(host, "ef-server-other")) {
            log.info("执行自定义的一致性哈希负载均衡算法");
            return consistencyHash.choose(exchange);
        } else if (StringUtils.equals(host, "ef-server-user")) {
            //return weightedRoundRobin.choose(exchange);
        }
        return super.choose(exchange);
    }
}
